#!/ur/bin/env ruby

require 'rubygems'
require 'activerecord'
require 'benchmark'
require 'logger'
require 'pp'

log_file=File.join(File.dirname(__FILE__),'log','mysql.log')
FileUtils.rm log_file,:force=>true

File.open(log_file,"w"){|f|
  f.puts "*"*60+$/
  f.puts "MySQL Store Performance Test".center(60,"*")+$/
  f.puts "*"*60+$/+$/+$/
}

#$log = Logger.new(File.join(File.dirname(__FILE__),'log','stdout.log'))
$log = Logger.new(log_file)
$log.level=Logger::ERROR

begin
  ActiveRecord::Base.establish_connection(
    :adapter =>"mysql",
    :username => "houyi",
    :password =>"111111",
    :database => "SNS",
    :host =>"10.250.6.30"
  )
  $log.info "MySQL Connect Success."
rescue => e
  $log.error "MySQL Connect Failed!"
  $log.error e.to_s
end

# N => count of iterations.
N=10000

class QaPost < ActiveRecord::Base
  set_table_name "qa_posts"
  set_primary_key "ID"
end

def insert_records(x=N)
  qp=QaPost.new
  QaPost.columns.each do |c|
    qp.send(c.to_s+"=",rand(x)) unless c=="ID"||c=='id'
  end
	ts=Benchmark.measure{qp.save!}
	`sync`
  $log.debug qp.inspect
  $log.info "One Record insert. ts=>#{ts.inspect}"
end

def select_record(id=1)
	qp=nil
	ts=Benchmark.measure{qp=QaPost.find_by_id(1)}
	$log.debug qp.inspect
	$log.info "One Record Select. ts=>#{ts.inspect}"
end


$log.info "#{N} iterations start.".center(60,'*')

ts = Benchmark.measure{
	N.times do |x|
		insert_records(x)
		select_record
	end
}

$log.info "#{N} iterations end.".center(60,'*')
$log.info "#{N} iterations cost ts=>#{ts.inspect}".center(60,'*')
